/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package main;

import bccomp.ByteParser;
import bccomp.LabelReduction;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Locale;
import tree.Context;
import tree.ProgramTree;

/**
 * Prekladac.
 */
public class Compiler {

    static {
        Locale.setDefault(Locale.US);
    }
    /**
     * Pouzit optimalizator?
     */
    

    public Compiler() {
        
    }

    /**
     * Prelozi soubor source. Vystup zapise do souboru dest.
     */
    public void compile(String source, String dest) throws IOException {
        LexAnalyzer lex = new LexAnalyzer(new FileReader(source));
        ParserAnalyzer p = new ParserAnalyzer(lex);
        ProgramTree t = p.program();
        SemanticAnalyzer sa = new SemanticAnalyzer();
        t.accept(sa);
        OutputStream os = new FileOutputStream(new File(dest));
        
        PrintWriter out = new PrintWriter(new FileWriter(dest+2));
        PrintWriter out2 = new PrintWriter(new FileWriter(dest+3));
        Context ctx = new ContextImpl(out2);
        ContextImplString ctxS = new ContextImplString();
        
         try {
           t.generate(ctx); 
        } finally {
            out2.close();
        }
         
        t.generate(ctxS);
         LabelReduction lr=new LabelReduction(ctxS.getOut());
         String reduced=lr.reduce();
         ByteParser.generateBytecode(reduced, os, lr.getMap());
         out.print(lr.reduce2());
         out.close();
         os.close();
        
    }
}
